﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TelnetRouterApplication.Model;
using TelnetRouterApplication.Control;

namespace TelnetRouterApplication.View
{
    public partial class RIPForm : UserControl
    {
        private List<IpModel> _networks;
        public List<IpModel> Networks
        {
            get
            {
                if (_networks == null)
                {
                    _networks = new List<IpModel>();
                }
                return _networks;
            }
            set { _networks = value; }
        }

        public RIPForm()
        {
            InitializeComponent();
            RefreshRouteList();
        }

        private void RefreshRouteList()
        {
            Networks = CommandHandler.GetInstance().GetSettings().RoutesRip;
            routeListBox.BeginUpdate();
            routeListBox.Items.Clear();
            foreach (IpModel network in Networks)
            {
                routeListBox.Items.Add(network);
            }
            routeListBox.EndUpdate();
        }

        private void addRouteBtn_Click(object sender, EventArgs e)
        {
            try
            {
                enableButtons(false);
                IpModel ip = new IpModel(tbNetwork.Text);
                bool success = CommandHandler.GetInstance().RouteRipAddNetworkCommand(ip);
                if (!success)
                {
                    MessageBox.Show("Erro ao inserir RIP");
                }

                RefreshRouteList();
            }
            finally
            {
                enableButtons(true);
            }
        }

        private void removeRouteBtn_Click(object sender, EventArgs e)
        {
            try
            {
                enableButtons(false);
                IpModel ip = (IpModel)routeListBox.SelectedItem;
                if (ip != null)
                {
                    CommandHandler.GetInstance().RouteRipDeleteNetworkCommand(ip);
                }
                RefreshRouteList();
            }
            finally
            {
                enableButtons(true);
            }
        }

        private void enableButtons(bool enable)
        {
            addRouteBtn.Enabled = enable;
            removeRouteBtn.Enabled = enable;
        }
    }
}
